using Magic.Redis;
using Magic.Application;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using Newtonsoft.Json.Serialization;

namespace Magic.Web.Entry;

/// <summary>
/// 测试类
/// </summary>
public class TestController : BaseTestController
{
    private static readonly string[] Summaries = new[]
    {
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

    private readonly ILogger<TestController> _logger;
    private readonly IJWTBuilder _jwtBuilder;
    private readonly ITestService _testService;
    private readonly IEventPublisher _eventPublisher;
    private readonly IRedisClient _redisClient;

    public TestController(ILogger<TestController> logger, IJWTBuilder jwtBuilder, ITestService testService,IEventPublisher eventPublisher, IRedisClient redisClient)
    {
        _logger = logger;
        this._jwtBuilder = jwtBuilder;
        _testService = testService;
        this._eventPublisher = eventPublisher;
        _redisClient = redisClient;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

    [HttpGet("login")]
    [AllowAnonymous]
    public async Task<string> Login()
    {
        string accessToken = _jwtBuilder.CreateToken(new Dictionary<string, object> {
            {ClaimConst.UserName, 10001},
            {ClaimConst.UserId, 20001},
            {ClaimConst.Account, "999999"}}
        );
        return accessToken;
    }

    [HttpGet("testException")]
    [AllowAnonymous]
    public async Task TestException()
    {
        WeatherForecast weatherForecast = null;
        weatherForecast.TemperatureC = 666;
    }

    [HttpGet("TestApiException")]
    [AllowAnonymous]
    public async Task TestApiException()
    {
        throw new ApiException("测试全局异常");

    }

    [HttpGet("getName")]
    [AllowAnonymous]
    public async Task<string> GetName()
    {
        return _testService.GetName();
    }

    [HttpGet("testEsLog")]
    [AllowAnonymous]
    public void TestESLog()
    {
        _logger.LogInformation($"{DateTime.Now}:我是错误");
    }


    [HttpGet("testLog")]
    [AllowAnonymous]
    public void TestLog() {
        Stopwatch stopwatch = Stopwatch.StartNew();
        for (int i = 0; i < 200000; i++)
        {
            _logger.LogError($"{i}:我是错误");
        }
        stopwatch.Stop();
        Console.WriteLine($"总共耗时:{stopwatch.Elapsed.TotalMilliseconds}");
        
        //Log.Information("我是info");
        //Log.Warning("我是警告");
        //Log.Debug("我是debug");
    }

    [HttpGet("testInfoLog")]
    [AllowAnonymous]
    public void TestInfoLog()
    {
        _logger.LogInformation("我是info");
        //Log.Warning("我是警告");
        //Log.Debug("我是debug");
    }

    [HttpGet("TestJson")]
    [AllowAnonymous]
    public WeatherForecast TestJson() { 
        WeatherForecast weatherForecast = new WeatherForecast();
        weatherForecast.Date = DateOnly.FromDateTime(DateTime.Now);
        weatherForecast.Summary = "夏天";
        weatherForecast.TemperatureC = 55;
        var aaa =  JsonConvert.SerializeObject(weatherForecast);
        return weatherForecast;
    }

    [HttpGet("TestEvenbus")]
    [AllowAnonymous]
    public void TestEvenbus()
    {
        WeatherForecast weatherForecast = new WeatherForecast();
        weatherForecast.Date = DateOnly.FromDateTime(DateTime.Now);
        weatherForecast.Summary = "夏天";
        weatherForecast.TemperatureC = 55;
        for (int i = 0; i < 1000000; i++)
        {
            weatherForecast.Summary =$"{i}：夏天";
            _eventPublisher.PublishAsync("Create:OpLog", weatherForecast);
        }
       
    }
    /// <summary>
    /// 测试orm
    /// </summary>
    /// <returns></returns>
    [HttpGet("TestOrm")]
    [AllowAnonymous]
    public async Task<SugarPagedList<SysUser>> TestOrm()
    {
        var list =await SugarContext.Instance.Queryable<SysUser>().ToPagedListAsync(1,10);
        return list;
    }

    /// <summary>
    /// 测试TestRedis
    /// </summary>
    /// <returns></returns>
    [HttpGet("TestRedis")]
    [AllowAnonymous]
    public async Task<WeatherForecast> TestRedis()
    {
        WeatherForecast weatherForecast = new WeatherForecast();
        weatherForecast.Date = DateOnly.FromDateTime(DateTime.Now);
        weatherForecast.Summary = "夏天";
        weatherForecast.TemperatureC = 55;
        _redisClient.HashSet("test:test1:test3", "test4", weatherForecast);

        return _redisClient.HashGet<WeatherForecast>("test:test1:test3", "test4");
    }



}

public class EventSubscriberTest : IEventSubscriber
{
    public EventSubscriberTest(IServiceProvider services)
    {
        Services = services;
    }

    public IServiceProvider Services { get; }

    [EventSubscribe("Create:OpLog")]
    public async Task CreateOpLog(EventHandlerExecutingContext context)
    {
        using var scope = Services.CreateScope();
        var _testService = scope.ServiceProvider.GetRequiredService<ITestService>();
        var payload = (WeatherForecast)context.Source.Payload;
        Console.WriteLine(JsonConvert.SerializeObject(payload));
        Console.WriteLine(_testService.GetName());
    }
}